package com.github.shiqiyue.rate.limiter.dao;

import com.github.shiqiyue.rate.limiter.entity.RateLimiterItem;
import org.springframework.util.AntPathMatcher;

import java.util.ArrayList;
import java.util.List;

/***
 * 流量控制信息-从内存中获得
 * 
 * @author wwy
 *
 */
public class InMemoryRateLimiterDao implements RateLimiterDao {
	
	private static List<RateLimiterItem> data = new ArrayList<>(10);
	
	private AntPathMatcher matcher = new AntPathMatcher();
	
	@Override
	public List<RateLimiterItem> matchItems(String path) {
		List<RateLimiterItem> result = new ArrayList<>(5);
		for (RateLimiterItem item : data) {
			if (matcher.match(item.getExpl(), path)) {
				result.add(item);
			}
		}
		return result;
		
	}
	
	public void insert(RateLimiterItem flowControlItem) {
		data.add(flowControlItem);
	}
	
	public void insertAll(List<RateLimiterItem> items) {
		data.addAll(items);
	}
	
	public void delete(String id) {
		Object[] items = data.stream().filter((item) -> {
			return id.equals(item.getId());
		}).toArray();
		if (items != null && items.length > 0) {
			for (Object item : items) {
				data.remove(item);
			}
		}
	}
	
	public List<RateLimiterItem> selectAll() {
		return data;
	}
	
}
